package com.msblearn.C_011;

import com.msblearn.C_010.M;
import sun.awt.windows.ThemeReader;

import java.util.Hashtable;
import java.util.UUID;
import java.util.concurrent.Exchanger;

/**
 * hashTable
 */
public class T001_TestHashTable {
    static Hashtable<UUID, UUID> table = new Hashtable<>();
    static int count = Constans.COUNT;
    static UUID[] keys = new UUID[count];
    static UUID[] values = new UUID[count];
    static final int table_count = Constans.TABLE_COUNT;

    static {
        for (int i=0;i<count;i++){
            keys[i] = UUID.randomUUID();
            values[i]  = UUID.randomUUID();
        }
    }

    static class MyThread extends Thread{
        int start;
        int gap = count/table_count;

        public MyThread(int start){
            this.start = start;
        }

        @Override
        public void run() {
          for(int i=start;i<start+gap;i++){
              table.put(keys[i],values[i]);
          }
        }
    }

    public static void main(String[] args) {

        //前面是插入
        long start = System.currentTimeMillis();
        Thread[] threads = new Thread[table_count];

        for(int i=0;i<threads.length;i++){
            threads[i] = new MyThread(i*(count/table_count));
        }

        for(Thread t :threads){
            t.start();
        }

        for(Thread td :threads){
            try {
                td.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        long end = System.currentTimeMillis();
        System.out.println(end -start);

        //后面是读取
        start = System.currentTimeMillis();
        for (int i=0;i<threads.length;i++){
            threads[i] = new Thread(()->{
               for(int j=0;j<1000000;j++){
                   table.get(keys[10]);
               }
            });
        }

        for(Thread t:threads){
            t.start();
        }
        for(Thread t:threads){
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        end = System.currentTimeMillis();
        System.out.println(end-start);
    }
}
